package com.everflourish.yeah100.act.menu;

import android.annotation.SuppressLint;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.design.widget.TextInputLayout;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Switch;
import android.widget.TextView;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.everflourish.yeah100.R;
import com.everflourish.yeah100.act.base.BaseFragment;
import com.everflourish.yeah100.act.welcome.LoginActivity;
import com.everflourish.yeah100.entity.CountryModel;
import com.everflourish.yeah100.entity.userinfo.UserInfo;
import com.everflourish.yeah100.http.ImageRequest;
import com.everflourish.yeah100.http.LoginAndRegisterRequest;
import com.everflourish.yeah100.http.SettingRequest;
import com.everflourish.yeah100.ui.ClearEditText;
import com.everflourish.yeah100.ui.dialog.LoadDialog;
import com.everflourish.yeah100.utils.KeyBoardUtils;
import com.everflourish.yeah100.utils.LogUtil;
import com.everflourish.yeah100.utils.MyToast;
import com.everflourish.yeah100.utils.SPUtil;
import com.everflourish.yeah100.utils.StringUtil;
import com.everflourish.yeah100.utils.SystemApp;
import com.everflourish.yeah100.utils.Yeah100;
import com.everflourish.yeah100.utils.constant.Constant;
import com.everflourish.yeah100.utils.constant.ResultCode;
import com.everflourish.yeah100.utils.constant.RoleEnum;

import org.json.JSONException;
import org.json.JSONObject;

import cn.smssdk.EventHandler;
import cn.smssdk.SMSSDK;
import cn.smssdk.UserInterruptException;

/**
 * 作者：Created by liqisi on 2016/8/16.
 * 时间：2016/8/16
 */
public class FragmentSetting extends BaseFragment implements View.OnClickListener {

    private TextView mNickNameTv, mMottoTv, mPhoneTv, mEmailTv, mUpdatePasswordTv, mRoleTv, mLogoutTv;
    private LinearLayout mNickNameLl, mMottoLl, mPhoneLl, mEmailLl, mUpdatePasswordLl;
    private Switch mConvertRoleSwitch;
    private SettingRequest mRequest;
    private SPUtil mSputil;
    private HomeActivity mActivity;
    private UserInfo mTempUserInfo;
    private int mAwaitTime = 60; // 重新获取验证码需要等待60秒
    // 是否中断获取验证码倒计时
    private static boolean isInterruptedCountdown = false;
    private CountryModel countryModel;
    private LoginAndRegisterRequest mLoginAndRegisterRequest;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_settting, container, false);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initData();
        initView();
        setUserInfo();
    }

    private void initData() {
        mContext = mActivity = (HomeActivity) getActivity();
        mRequest = SettingRequest.getInstance();
        mLoginAndRegisterRequest = LoginAndRegisterRequest.getInstance();
        countryModel = new CountryModel();
        countryModel.setName("中国");
        countryModel.setOrder("42");
        countryModel.setZone("86");
        SMSSDK.initSDK(mContext, Constant.MOB_APP_KEY, Constant.MOB_APP_SECRET);
        SMSSDK.registerEventHandler(eh);
    }

    private void initView() {
        mNickNameTv = (TextView) getView().findViewById(R.id.setting_nickname_tv);
        mNickNameLl = (LinearLayout) getView().findViewById(R.id.setting_nickname_ll);
        mMottoTv = (TextView) getView().findViewById(R.id.setting_motto_tv);
        mMottoLl = (LinearLayout) getView().findViewById(R.id.setting_motto_ll);
        mPhoneTv = (TextView) getView().findViewById(R.id.setting_phone_tv);
        mPhoneLl = (LinearLayout) getView().findViewById(R.id.setting_phone_ll);
        mEmailTv = (TextView) getView().findViewById(R.id.setting_email_tv);
        mEmailLl = (LinearLayout) getView().findViewById(R.id.setting_email_ll);
        mUpdatePasswordLl = (LinearLayout) getView().findViewById(R.id.setting_password_ll);
        mUpdatePasswordTv = (TextView) getView().findViewById(R.id.setting_update_password);
        mLogoutTv = (TextView) getView().findViewById(R.id.setting_logout_tv);
        mRoleTv = (TextView) getView().findViewById(R.id.setting_role_tv);
        mConvertRoleSwitch = (Switch) getView().findViewById(R.id.setting_convert_switch);
        mNickNameLl.setOnClickListener(this);
        mMottoLl.setOnClickListener(this);
        mPhoneLl.setOnClickListener(this);
        mEmailLl.setOnClickListener(this);
//        mUpdatePasswordTv.setOnClickListener(this);
        mUpdatePasswordLl.setOnClickListener(this);
        mLogoutTv.setOnClickListener(this);
        if (Yeah100.mRoleEnum == RoleEnum.TEACHER) {  // 老师身份
            mRoleTv.setText("老师");
            mConvertRoleSwitch.setChecked(true);
        } else {   //  学生身份
            mRoleTv.setText("学生");
            mConvertRoleSwitch.setChecked(false);
        }
        mConvertRoleSwitch.setOnCheckedChangeListener(new MyCheckedChangeListener());
    }

    private void setUserInfo() {
        UserInfo userInfo = Yeah100.loginInfo.userInfo;
        if (TextUtils.isEmpty(userInfo.nickName)) {
            mNickNameTv.setText("空");
        } else {
            mNickNameTv.setText(userInfo.nickName);
        }
        if (TextUtils.isEmpty(userInfo.phoneNo)) {
            mPhoneTv.setText("空");
        } else {
            mPhoneTv.setText(userInfo.phoneNo);
        }
        if (TextUtils.isEmpty(userInfo.email)) {
            mEmailTv.setText("空");
        } else {
            mEmailTv.setText(userInfo.email);
        }
        if (TextUtils.isEmpty(userInfo.motto)) {
            mMottoTv.setText("空");
        } else {
            mMottoTv.setText(userInfo.motto);
        }
    }

    /**
     * 设置一个临时的userInfo.备份
     */
    private void setTempUserInfo() {
        mTempUserInfo = new UserInfo();
        mTempUserInfo.id = Yeah100.loginInfo.userInfo.id;
        mTempUserInfo.name = Yeah100.loginInfo.userInfo.name;
        mTempUserInfo.nickName = Yeah100.loginInfo.userInfo.nickName;
        mTempUserInfo.motto = Yeah100.loginInfo.userInfo.motto;
        mTempUserInfo.photoId = Yeah100.loginInfo.userInfo.photoId;
        mTempUserInfo.phoneNo = Yeah100.loginInfo.userInfo.phoneNo;
        mTempUserInfo.email = Yeah100.loginInfo.userInfo.email;
        mTempUserInfo.lastLoginOn = Yeah100.loginInfo.userInfo.lastLoginOn;
        mTempUserInfo.classId = Yeah100.loginInfo.userInfo.classId;
        mTempUserInfo.className = Yeah100.loginInfo.userInfo.className;
    }

    private class MyCheckedChangeListener implements CompoundButton.OnCheckedChangeListener {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, final boolean isChecked) {
            String message = "";
            if (Yeah100.mRoleEnum == RoleEnum.TEACHER) {  // 老师身份
                message = "是否要切换为学生身份？";
            } else {   //  学生身份
                message = "是否要切换为老师身份？";
            }
            AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
            builder.setMessage(message);
            builder.setPositiveButton("切换", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            });
            builder.setNegativeButton("否", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    mConvertRoleSwitch.setOnCheckedChangeListener(null);
                    mConvertRoleSwitch.setChecked(!isChecked);
                    mConvertRoleSwitch.setOnCheckedChangeListener(new MyCheckedChangeListener());
                    dialog.dismiss();
                }
            });
            builder.setCancelable(false);
            builder.show();
        }
    }

    /**
     * 获取短信handler
     */
    static EventHandler eh = new EventHandler() {
        @Override
        public void afterEvent(final int event, final int result, final Object data) {
            Message message = new Message();
            message.arg2 = event;
            message.arg1 = result;
            message.obj = data;
            mHandler.sendMessage(message);
        }
    };

    @SuppressLint("HandlerLeak")
    @SuppressWarnings("unchecked")
    static
    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            int result = msg.arg1;
            int event = msg.arg2;
            Object data = msg.obj;
            if (result == SMSSDK.RESULT_COMPLETE) {
                if (event == SMSSDK.EVENT_GET_SUPPORTED_COUNTRIES) {
                } else if (event == SMSSDK.EVENT_GET_VERIFICATION_CODE) {// 目前，手机端发送验证码已弃用。
                    MyToast.showShort(mContext, "验证码已发送至你的手机");
                } else if (event == SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE) {// 目前，手机端发送验证码已弃用。
                }
            } else {
                if (event == SMSSDK.EVENT_GET_VERIFICATION_CODE && data != null
                        && (data instanceof UserInterruptException)) {
                    return;
                }
                try {
                    ((Throwable) data).printStackTrace();
                    Throwable throwable = (Throwable) data;
                    JSONObject object = new JSONObject(throwable.getMessage());
                    String des = object.optString("detail");
                    String description = object.optString("description");
                    if (!TextUtils.isEmpty(des)) {
                        MyToast.showShort(mContext, des);
                        isInterruptedCountdown = true;
                        return;
                    }
                } catch (Exception e) {
                    LogUtil.e("", e);
                }
                MyToast.showShort(mContext, "网络异常，请稍后重试");
            }
            SMSSDK.unregisterEventHandler(eh);
        }
    };

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.setting_nickname_ll:
                setUserInfoDialog("nickname");
                break;
            case R.id.setting_motto_ll:
                setUserInfoDialog("motto");
                break;
            case R.id.setting_phone_ll:
                setTelPhoneDialog();
                break;
            case R.id.setting_email_ll:
                setEmailDialog();
                break;
            case R.id.setting_password_ll:
                setUpdatePasswordDialog();
                break;
            case R.id.setting_logout_tv:
                AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
                builder.setMessage("是否要退出当前账号？");
                builder.setPositiveButton("退出", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        logoutRequest();
                    }
                });
                builder.setNegativeButton("否", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
                builder.show();
                break;
        }
    }

    /**
     * 修改昵称，座右铭对话框
     */
    private void setUserInfoDialog(final String infoFlag) {
        LayoutInflater inflater = LayoutInflater.from(mContext);
        LinearLayout updateNicknameLl = (LinearLayout) inflater.inflate(R.layout.dialog_setting_nickname, null);
        final TextInputLayout nickNameTil = (TextInputLayout) updateNicknameLl.findViewById(R.id.setting_nickname_update_til);
        final EditText nickNameEt = (EditText) updateNicknameLl.findViewById(R.id.setting_nickname_update_et);
        TextView nickNameTv = (TextView) updateNicknameLl.findViewById(R.id.setting_update_title);
        if (infoFlag.equals("nickname")) {
            nickNameTv.setText("修改昵称");
            nickNameTil.setHint("昵称");
            if (TextUtils.isEmpty(Yeah100.loginInfo.userInfo.nickName)) {
                nickNameTv.setHint("昵称");
            } else {
                nickNameEt.setText(Yeah100.loginInfo.userInfo.nickName);
                nickNameEt.setSelection(nickNameEt.getText().toString().length());
            }
        } else if (infoFlag.equals("motto")) {
            nickNameTv.setText("修改座右铭");
            nickNameTil.setHint("座右铭");
            if (TextUtils.isEmpty(Yeah100.loginInfo.userInfo.motto)) {
                nickNameEt.setHint("");
//                nickNameTil.setHint("座右铭");
            } else {
                nickNameEt.setText(Yeah100.loginInfo.userInfo.motto);
                nickNameEt.setSelection(nickNameEt.getText().toString().length());
            }
        }
        final AlertDialog dialog = new AlertDialog.Builder(mContext).setView(updateNicknameLl)
                .setPositiveButton("确定", null)
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        KeyBoardUtils.closeKeybord(nickNameEt, mContext);
                        dialog.dismiss();
                    }
                }).create();
        dialog.setCancelable(false);
        dialog.show();
        dialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                KeyBoardUtils.closeKeybord(nickNameEt, mContext);
                final String nickNameStr = nickNameEt.getText().toString();
                if (infoFlag.equals("nickname")) {
                    if (nickNameStr.length() > 32) {
                        nickNameTil.setError("昵称格式：0~32个字符");
                        return;
                    } else {
                        nickNameTil.setErrorEnabled(false);
                        nickNameTil.setError(null);
                        setTempUserInfo();
                    }
                    Yeah100.loginInfo.userInfo.nickName = nickNameStr;
                    userInfoUpdateRequest(Yeah100.loginInfo.userInfo);
                    dialog.dismiss();
                } else if (infoFlag.equals("motto")) {
                    if (nickNameStr.length() > 100) {
                        nickNameTil.setError("座右铭格式：0~100个字符");
                        return;
                    } else {
                        nickNameTil.setErrorEnabled(false);
                        nickNameTil.setError(null);
                        setTempUserInfo();
                    }
                    Yeah100.loginInfo.userInfo.motto = nickNameStr;
                    userInfoUpdateRequest(Yeah100.loginInfo.userInfo);
                    dialog.dismiss();
                }
            }
        });
        KeyBoardUtils.openKeybord(nickNameEt, mContext);
    }

    /**
     * 修改手机号码对话框
     */
    private void setTelPhoneDialog() {
        LayoutInflater inflater = LayoutInflater.from(mContext);
        LinearLayout updateNicknameLl = (LinearLayout) inflater.inflate(R.layout.dialog_setting_phone, null);
        final TextInputLayout phoneNumTil = (TextInputLayout) updateNicknameLl.findViewById(R.id.setting_update_phone_til);
        final ClearEditText phoneNumEt = (ClearEditText) updateNicknameLl.findViewById(R.id.setting_update_phone_et);
        final TextInputLayout verificationTil = (TextInputLayout) updateNicknameLl.findViewById(R.id.setting_update_verification_til);
        final ClearEditText verificationEt = (ClearEditText) updateNicknameLl.findViewById(R.id.setting_update_verification_et);
        final TextView mVerificationTv = (TextView) updateNicknameLl.findViewById(R.id.setting_update_verification_tv);
        mVerificationTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switch (v.getId()) {
                    case R.id.setting_update_verification_tv:
                        getVerificationCode(phoneNumEt.getText().toString(), phoneNumTil, mVerificationTv);
                        break;
                    default:
                        break;
                }
            }
        });
        final AlertDialog dialog = new AlertDialog.Builder(mContext).setView(updateNicknameLl)
                .setPositiveButton("确定", null)
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        KeyBoardUtils.closeKeybord(verificationEt, mContext);
                        dialog.dismiss();
                    }
                }).create();
        dialog.setCancelable(false);
        dialog.show();
        dialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String verificationCodeStr = verificationEt.getText().toString().trim();
                if (TextUtils.isEmpty(verificationCodeStr)) {
                    verificationTil.setError("请输入验证码");
                    return;
                } else {
                    verificationTil.setErrorEnabled(false);
                    verificationTil.setError(null);
                }
                setTempUserInfo();
                Yeah100.loginInfo.userInfo.phoneNo = phoneNumEt.getText().toString();
                userSettingUpdatePhoneRequest(phoneNumEt.getText().toString(), countryModel.getZone(),
                        verificationEt.getText().toString(), dialog);
                KeyBoardUtils.closeKeybord(verificationEt, mContext);

            }
        });
        KeyBoardUtils.openKeybord(phoneNumEt, mContext);
    }

    /**
     * 修改邮箱对话框
     */
    private void setEmailDialog() {
        LayoutInflater inflater = LayoutInflater.from(mContext);
        LinearLayout updateNicknameLl = (LinearLayout) inflater.inflate(R.layout.dialog_setting_email, null);
        final TextInputLayout emailTil = (TextInputLayout) updateNicknameLl.findViewById(R.id.setting_update_email_til);
        final ClearEditText emailEt = (ClearEditText) updateNicknameLl.findViewById(R.id.setting_update_email_et);
        final TextInputLayout phoneNumTil = (TextInputLayout) updateNicknameLl.findViewById(R.id.setting_update_email_phone_til);
        final ClearEditText phoneNumEt = (ClearEditText) updateNicknameLl.findViewById(R.id.setting_update_email_phone_et);
        final TextInputLayout verificationTil = (TextInputLayout) updateNicknameLl.findViewById(R.id.setting_update_email_verification_til);
        final ClearEditText verificationEt = (ClearEditText) updateNicknameLl.findViewById(R.id.setting_update_email_verification_et);
        final TextView mVerificationTv = (TextView) updateNicknameLl.findViewById(R.id.setting_update_email_verification_tv);
        mVerificationTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switch (v.getId()) {
                    case R.id.setting_update_email_verification_tv:
                        getEmailVerificationCode(phoneNumEt.getText().toString(), phoneNumTil, mVerificationTv);
                        break;
                    default:
                        break;
                }
            }
        });
        final AlertDialog dialog = new AlertDialog.Builder(mContext).setView(updateNicknameLl)
                .setPositiveButton("确定", null)
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        KeyBoardUtils.closeKeybord(verificationEt, mContext);
                        dialog.dismiss();
                    }
                }).create();
        dialog.setCancelable(false);
        dialog.show();
        dialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String emailStr = emailEt.getText().toString().trim();
                if (TextUtils.isEmpty(emailStr)) {
                    emailTil.setError("请输入新邮箱");
                    return;
                } else if (!StringUtil.isEmail(emailStr)) {
                    emailTil.setError("邮箱格式有误，请重新输入");
                    return;
                } else {
                    emailTil.setErrorEnabled(false);
                    emailTil.setError(null);
                }
                String verificationCodeStr = verificationEt.getText().toString().trim();
                if (TextUtils.isEmpty(verificationCodeStr)) {
                    verificationTil.setError("请输入验证码");
                    return;
                } else {
                    verificationTil.setErrorEnabled(false);
                    verificationTil.setError(null);
                }
                setTempUserInfo();
                Yeah100.loginInfo.userInfo.email = emailEt.getText().toString();
                userSettingUpdateEmailRequest(phoneNumEt.getText().toString(), countryModel.getZone(),
                        verificationEt.getText().toString(), emailStr, dialog);
                KeyBoardUtils.closeKeybord(verificationEt, mContext);
            }
        });
        KeyBoardUtils.openKeybord(phoneNumEt, mContext);
    }

    /**
     * 修改密码对话框
     */
    private void setUpdatePasswordDialog() {
        LayoutInflater inflater = LayoutInflater.from(mContext);
        LinearLayout updateNicknameLl = (LinearLayout) inflater.inflate(R.layout.dialog_setting_password, null);
        final TextInputLayout oldPasswordTil = (TextInputLayout) updateNicknameLl.findViewById(R.id.setting_update_old_password_til);
        final ClearEditText oldPasswordEt = (ClearEditText) updateNicknameLl.findViewById(R.id.setting_update_old_password_et);
        final TextInputLayout newPasswordTil = (TextInputLayout) updateNicknameLl.findViewById(R.id.setting_update_new_password_til);
        final ClearEditText newPasswordEt = (ClearEditText) updateNicknameLl.findViewById(R.id.setting_update_new_password_et);
        final TextInputLayout confirmPasswordTil = (TextInputLayout) updateNicknameLl.findViewById(R.id.setting_update_confirm_password_til);
        final ClearEditText confirmPasswordEt = (ClearEditText) updateNicknameLl.findViewById(R.id.setting_update_confirm_password_et);
        final AlertDialog dialog = new AlertDialog.Builder(mContext).setView(updateNicknameLl)
                .setPositiveButton("确定", null)
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        KeyBoardUtils.closeKeybord(confirmPasswordEt, mContext);
                        dialog.dismiss();
                    }
                }).create();
        dialog.setCancelable(false);
        dialog.show();
        dialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String oldPasswordStr = oldPasswordEt.getText().toString().trim();
                if (TextUtils.isEmpty(oldPasswordStr)) {
                    oldPasswordTil.setError("请输入密码");
                    return;
                } else if (!StringUtil.isPassword(oldPasswordStr)) {
                    oldPasswordTil.setError("6-20位字符，支持数字和字母，区分大小写");
                    return;
                } else {
                    oldPasswordTil.setErrorEnabled(false);
                    oldPasswordTil.setError(null);
                }
                String newPasswordStr = newPasswordEt.getText().toString().trim();
                if (TextUtils.isEmpty(newPasswordStr)) {
                    newPasswordTil.setError("请输入新密码");
                    return;
                } else if (!StringUtil.isPassword(newPasswordStr)) {
                    newPasswordTil.setError("6-20位字符，支持数字和字母，区分大小写");
                    return;
                } else {
                    newPasswordTil.setErrorEnabled(false);
                    newPasswordTil.setError(null);
                }
                String confirmPasswordStr = confirmPasswordEt.getText().toString().trim();
                if (TextUtils.isEmpty(confirmPasswordStr)) {
                    confirmPasswordTil.setError("请输入确认密码");
                    return;
                } else if (!newPasswordStr.equals(confirmPasswordStr)) {
                    confirmPasswordTil.setError("两次输入的密码不一致");
                    return;
                } else {
                    confirmPasswordTil.setErrorEnabled(false);
                    confirmPasswordTil.setError(null);
                }
                KeyBoardUtils.closeKeybord(oldPasswordEt, mContext);
                updatePwdRequest(oldPasswordStr, newPasswordStr, dialog);
            }
        });
        KeyBoardUtils.openKeybord(oldPasswordEt, mContext);
    }

    /**
     * 修改密码请求
     *
     * @param oldPwd
     * @param newPwd
     */
    private void updatePwdRequest(String oldPwd, String newPwd, final AlertDialog dialog) {
        mLoadDialog = LoadDialog.show(mContext, null, "正在修改...", false);
        JsonObjectRequest request = mRequest.updatePwdRequest(oldPwd, newPwd,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        updatePwdListener(response, dialog);
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        mRequest.disposeError(mContext, mLoadDialog, error, "修改密码失败");
                    }
                });
        mQueue.add(request);
    }

    /**
     * 修改昵称，个性签名请求
     *
     * @param userInfo
     */
    private void userInfoUpdateRequest(UserInfo userInfo) {
        mLoadDialog = LoadDialog.show(mContext, null, "正在修改...", false);
        final JsonObjectRequest userInfoUpdateRequest = mRequest.userInfoUpdateRequest(userInfo,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        userInfoUpdateListener(response);
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Yeah100.loginInfo.userInfo = mTempUserInfo;
                        mRequest.disposeError(mContext, mLoadDialog, error, "修改失败");
                    }
                });
        mQueue.add(userInfoUpdateRequest);
    }

    /**
     * 注销账号请求
     */
    public void logoutRequest() {
        mLoadDialog = LoadDialog.show(mContext, null, "正在退出...", false);
        JsonObjectRequest request = mRequest.logoutRequest(
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        logoutListener(response);
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        MyToast.showLong(mContext, "退出当前账号失败");
                    }
                });
        mQueue.add(request);
    }

    /**
     * 修改邮箱获取验证码倒数线程
     */
    private void getEmailVerificationCode(String mPhoneNumber, TextInputLayout phoneNumTil, TextView mVerificationTv) {
        if (TextUtils.isEmpty(mPhoneNumber)) {
            phoneNumTil.setError("请输入手机号码");
            return;
        } else if (!StringUtil.isPhoneNo(mPhoneNumber)) {
            phoneNumTil.setError("手机号码格式有误，请重新输入");
            return;
        } else {
            phoneNumTil.setErrorEnabled(false);
            phoneNumTil.setError(null);
        }
        getEmailVerificationCodeRequest(countryModel.getZone(), mPhoneNumber, mVerificationTv);
    }

    /**
     * 修改手机号获取验证码倒数线程
     */
    private void getVerificationCode(String mPhoneNumber, TextInputLayout phoneNumTil, TextView mVerificationTv) {
        if (TextUtils.isEmpty(mPhoneNumber)) {
            phoneNumTil.setError("请输入手机号码");
            return;
        } else if (!StringUtil.isPhoneNo(mPhoneNumber)) {
            phoneNumTil.setError("手机号码格式有误，请重新输入");
            return;
        } else {
            phoneNumTil.setErrorEnabled(false);
            phoneNumTil.setError(null);
        }
        getPhoneVerificationCodeRequest(countryModel.getZone(), mPhoneNumber, mVerificationTv);
    }

    /**
     * 修改邮箱获取手机验证码
     *
     * @param phoneZone 区号 如：86
     * @param phoneNo   手机号码
     */
    private void getEmailVerificationCodeRequest(String phoneZone, final String phoneNo, final TextView mVerificationTv) {
        JsonObjectRequest request = mLoginAndRegisterRequest.getPasswordPhoneVerificationCodeRequest(
                phoneZone, phoneNo, new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        emailVerificationCodeListener(response, mVerificationTv, phoneNo);
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        mRequest.disposeError(mContext, mLoadDialog, error, "发送验证码失败");
                    }
                });
        mQueue.add(request);
    }

    /**
     * 修改手机号获取手机验证码
     *
     * @param phoneZone 区号 如：86
     * @param phoneNo   手机号码
     */
    private void getPhoneVerificationCodeRequest(String phoneZone, final String phoneNo, final TextView mVerificationTv) {
        JsonObjectRequest request = mLoginAndRegisterRequest.getVerificationCodeRequest(
                phoneZone, phoneNo, new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        phoneVerificationCodeListener(response, mVerificationTv, phoneNo);
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        mRequest.disposeError(mContext, mLoadDialog, error, "发送验证码失败");
                    }
                });
        mQueue.add(request);
    }

    /**
     * 用户邮箱修改
     *
     * @param phoneNo
     * @param phoneZone
     * @param verificationCode
     */
    private void userSettingUpdateEmailRequest(String phoneNo, String phoneZone, String verificationCode,
                                               String email, final AlertDialog dialog) {
        mLoadDialog = LoadDialog.show(mContext, null, "正在修改...");
        JsonObjectRequest request = mRequest.userSettingUpdateEmailRequest(phoneNo, phoneZone, verificationCode, email,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        userSettingUpdateEmailListener(response, dialog);
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        mRequest.disposeError(mContext, mLoadDialog, error, "修改邮箱失败");
                    }
                });
        mQueue.add(request);
    }

    /**
     * 用户手机号码修改
     *
     * @param phoneNo
     * @param phoneZone
     * @param verificationCode
     */
    private void userSettingUpdatePhoneRequest(String phoneNo, String phoneZone, String verificationCode, final AlertDialog dialog) {
        mLoadDialog = LoadDialog.show(mContext, null, "正在修改...");
        JsonObjectRequest request = mRequest.userSettingUpdatePhoneRequest(phoneNo, phoneZone, verificationCode,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        userSettingUpdatePhoneListener(response, dialog);
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        mRequest.disposeError(mContext, mLoadDialog, error, "修改手机号码失败");
                    }
                });
        mQueue.add(request);
    }

    /**
     * 修改密码监听
     *
     * @param response
     * @param dialog
     */
    private void updatePwdListener(JSONObject response, AlertDialog dialog) {
        try {
            String resultCode = response.getString(Constant.RESULT_CODE);
            if (resultCode.equals(ResultCode.result_ok.resultCode)) {
                dialog.dismiss();
                MyToast.showShort(mContext, "修改成功");
            } else if (resultCode.equals(ResultCode.result_000001E.resultCode)) {
                MyToast.showShort(mContext, R.string.user_info_03031_000001E);
            } else if (resultCode.equals(ResultCode.result_100014E.resultCode)) {
                MyToast.showShort(mContext, R.string.user_info_03032_100014E);
            } else if (resultCode.equals(ResultCode.result_system_exception_999999E)) {
                MyToast.showShort(mContext, R.string.user_info_030399_999999E);
            } else {
                MyToast.showShort(mContext, "修改密码失败成功");
            }
        } catch (JSONException e) {
            LogUtil.e("JSON异常", e);
            MyToast.showShort(mContext, "修改密码失败成功");
        } finally {
            LoadDialog.dismiss(mLoadDialog);
        }
    }

    /**
     * 修改邮箱获取手机验证码监听
     *
     * @param response
     */
    private void emailVerificationCodeListener(JSONObject response, TextView mVerificationTv, String phone) {
        String resultCode = "";
        try {
            resultCode = response.getString(Constant.RESULT_CODE);
            if (resultCode.equals(ResultCode.result_ok.resultCode)) {
                MyToast.showShort(mContext, "验证码已发送至你的手机");
                sendPhoneMessage(mVerificationTv, phone);
            } else if (resultCode
                    .equals(ResultCode.result_000001E.resultCode)) {
                MyToast.showShort(mContext, R.string.regist_01021_000001E);
            } else if (resultCode
                    .equals(ResultCode.result_100005E.resultCode)) {
                MyToast.showShort(mContext, R.string.regist_01022_100005E);
            } else if (resultCode
                    .equals(ResultCode.result_100017E.resultCode)) {
                MyToast.showShort(mContext, R.string.regist_01023_100017E);
            } else if (resultCode
                    .equals(ResultCode.result_100019E.resultCode)) {
                MyToast.showShort(mContext, R.string.regist_01023_100019E);
            } else if (resultCode
                    .equals(ResultCode.result_system_exception_999999E.resultCode)) {
                MyToast.showShort(mContext, R.string.regist_010299_999999E);
            } else {
                MyToast.showShort(mContext, "发送验证码失败");
            }
        } catch (JSONException e1) {
            e1.printStackTrace();
            MyToast.showShort(mContext, "发送验证码失败");
        } finally {
        }
    }

    /**
     * 修改手机号获取手机验证码监听
     *
     * @param response
     */
    private void phoneVerificationCodeListener(JSONObject response, TextView mVerificationTv, String phone) {
        String resultCode = "";
        try {
            resultCode = response.getString(Constant.RESULT_CODE);
            if (resultCode.equals(ResultCode.result_ok.resultCode)) {
                MyToast.showShort(mContext, "验证码已发送至你的手机");
                sendPhoneMessage(mVerificationTv, phone);
            } else if (resultCode
                    .equals(ResultCode.result_000001E.resultCode)) {
                MyToast.showShort(mContext, R.string.regist_01021_000001E);
            } else if (resultCode
                    .equals(ResultCode.result_100005E.resultCode)) {
                MyToast.showShort(mContext, R.string.regist_01022_100005E);
            } else if (resultCode
                    .equals(ResultCode.result_100017E.resultCode)) {
                MyToast.showShort(mContext, R.string.regist_01023_100017E);
            } else if (resultCode
                    .equals(ResultCode.result_system_exception_999999E.resultCode)) {
                MyToast.showShort(mContext, R.string.regist_010299_999999E);
            } else {
                MyToast.showShort(mContext, "发送验证码失败");
            }
        } catch (JSONException e1) {
            e1.printStackTrace();
            MyToast.showShort(mContext, "发送验证码失败");
        } finally {
        }
    }

    /**
     * 修改昵称，个性签名监听
     *
     * @param response
     */
    private void userInfoUpdateListener(JSONObject response) {
        String resultCode = "";
        try {
            resultCode = response.getString(Constant.RESULT_CODE);
            if (resultCode.equals(ResultCode.result_ok.resultCode)) {
                setUserInfo();
                MyToast.showLong(mContext, "修改成功");
            } else if (resultCode
                    .equals(ResultCode.result_000001E.resultCode)) {
                MyToast.showShort(mContext, R.string.user_info_03021_000001E);
            } else if (resultCode
                    .equals(ResultCode.result_100012E.resultCode)) {
                MyToast.showShort(mContext, R.string.user_info_03022_100012E);
            } else if (resultCode
                    .equals(ResultCode.result_100002E.resultCode)) {
                MyToast.showShort(mContext, R.string.user_info_03023_100002E);
            } else if (resultCode
                    .equals(ResultCode.result_100005E.resultCode)) {
                MyToast.showShort(mContext, R.string.user_info_03024_100005E);
            } else if (resultCode
                    .equals(ResultCode.result_100013E.resultCode)) {
                MyToast.showShort(mContext, R.string.user_info_03025_100013E);
            } else if (resultCode
                    .equals(ResultCode.result_system_exception_999999E.resultCode)) {
                MyToast.showShort(mContext, R.string.user_info_030299_999999E);
            } else {
                MyToast.showShort(mContext, "修改失败");
            }
        } catch (JSONException e) {
            LogUtil.e("JSON异常", e);
        } finally {
            LoadDialog.dismiss(mLoadDialog);
            if (!resultCode.equals(ResultCode.result_ok.resultCode)) {
                Yeah100.loginInfo.userInfo = mTempUserInfo;
            }
        }
    }

    /**
     * 注销监听
     *
     * @param response
     */
    private void logoutListener(JSONObject response) {
        String resultCode = "";
        try {
            resultCode = response.getString(Constant.RESULT_CODE);
            if (resultCode.equals(ResultCode.result_ok.resultCode)) {
                ImageRequest.init();
                mQueue.stop();
                SystemApp.getInstance().exitSystem();
                LogUtil.d("logout success");
                Intent intent = new Intent(mContext, LoginActivity.class);
                startActivity(intent);
                mActivity.finish();
                mSputil = SPUtil.getSharedPreferences(mContext, SPUtil.FILE_NAME);
                mSputil.remove(SPUtil.PASSWORD);
            } else {
                MyToast.showLong(mContext, "退出当前账号失败");
            }
        } catch (JSONException e) {
            e.printStackTrace();
        } finally {
            LoadDialog.dismiss(mLoadDialog);
        }
    }

    /**
     * 修改手机号码监听
     *
     * @param response
     */
    private void userSettingUpdatePhoneListener(JSONObject response, AlertDialog dialog) {
        String resultCode = "";
        try {
            resultCode = response.getString(Constant.RESULT_CODE);
            if (resultCode.equals(ResultCode.result_ok.resultCode)) {
                setUserInfo();
                dialog.dismiss();
                MyToast.showShort(mContext, "修改成功");
            } else if (resultCode
                    .equals(ResultCode.result_000001E.resultCode)) {
                MyToast.showShort(mContext, R.string.user_info_03153_000001E);
            } else if (resultCode
                    .equals(ResultCode.result_100012E.resultCode)) {
                MyToast.showShort(mContext, R.string.user_info_03152_000012E);
            } else if (resultCode
                    .equals(ResultCode.result_100005E.resultCode)) {
                MyToast.showShort(mContext, R.string.user_info_03154_100005E);
            } else if (resultCode
                    .equals(ResultCode.result_100017E.resultCode)) {
                MyToast.showShort(mContext, R.string.user_info_03155_100017E);
            } else if (resultCode
                    .equals(ResultCode.result_100007E.resultCode)) {
                MyToast.showShort(mContext, R.string.user_info_03156_100007E);
            } else if (resultCode
                    .equals(ResultCode.result_100019E.resultCode)) {
                MyToast.showShort(mContext, R.string.user_info_03157_100019E);
            } else if (resultCode
                    .equals(ResultCode.result_100020E.resultCode)) {
                MyToast.showShort(mContext, R.string.user_info_03158_100020E);
            } else if (resultCode
                    .equals(ResultCode.result_system_exception_999999E.resultCode)) {
                MyToast.showShort(mContext, R.string.user_info_030299_999999E);
            } else {
                MyToast.showShort(mContext, "修改手机号码失败");
            }
        } catch (JSONException e) {
            e.printStackTrace();
            MyToast.showShort(mContext, "修改手机号码失败");
        } finally {
            LoadDialog.dismiss(mLoadDialog);
            if (!resultCode.equals(ResultCode.result_ok.resultCode)) {
                Yeah100.loginInfo.userInfo = mTempUserInfo;
            }
        }
    }

    /**
     * 修改邮箱监听
     *
     * @param response
     */
    private void userSettingUpdateEmailListener(JSONObject response, AlertDialog dialog) {
        String resultCode = "";
        try {
            resultCode = response.getString(Constant.RESULT_CODE);
            if (resultCode.equals(ResultCode.result_ok.resultCode)) {
                setUserInfo();
                dialog.dismiss();
                MyToast.showShort(mContext, "修改成功");
            } else if (resultCode
                    .equals(ResultCode.result_000001E.resultCode)) {
                MyToast.showShort(mContext, R.string.user_info_03153_000001E);
            } else if (resultCode
                    .equals(ResultCode.result_100012E.resultCode)) {
                MyToast.showShort(mContext, R.string.user_info_03152_000012E);
            } else if (resultCode
                    .equals(ResultCode.result_100004E.resultCode)) {
                MyToast.showShort(mContext, R.string.user_info_03155_100004E);
            } else if (resultCode
                    .equals(ResultCode.result_100017E.resultCode)) {
                MyToast.showShort(mContext, R.string.user_info_03155_100017E);
            } else if (resultCode
                    .equals(ResultCode.result_100007E.resultCode)) {
                MyToast.showShort(mContext, R.string.user_info_03156_100007E);
            } else if (resultCode
                    .equals(ResultCode.result_100019E.resultCode)) {
                MyToast.showShort(mContext, R.string.user_info_03157_100019E);
            } else if (resultCode
                    .equals(ResultCode.result_100020E.resultCode)) {
                MyToast.showShort(mContext, R.string.user_info_03158_100020E);
            } else if (resultCode
                    .equals(ResultCode.result_system_exception_999999E.resultCode)) {
                MyToast.showShort(mContext, R.string.user_info_030299_999999E);
            } else {
                MyToast.showShort(mContext, "修改邮箱失败");
            }
        } catch (JSONException e) {
            e.printStackTrace();
            MyToast.showShort(mContext, "修改邮箱失败");
        } finally {
            LoadDialog.dismiss(mLoadDialog);
            if (!resultCode.equals(ResultCode.result_ok.resultCode)) {
                Yeah100.loginInfo.userInfo = mTempUserInfo;
            }
        }
    }

    private void sendPhoneMessage(final TextView mVerificationTv, String phone) {
//        SMSSDK.getVerificationCode(countryModel.getZone(), phone);
        new AsyncTask<Void, Integer, Void>() {
            @SuppressWarnings("deprecation")
            @Override
            protected void onPreExecute() {
                // 点击获取验证码后：点击无效
                mVerificationTv.setClickable(false);
                isInterruptedCountdown = false;
            }

            @Override
            protected Void doInBackground(Void... params) {
                try {
                    for (int i = mAwaitTime; i > 0; i--) {
                        publishProgress(i);
                        Thread.sleep(1000);
                        if (isInterruptedCountdown) {
                            break;
                        }
                    }
                } catch (InterruptedException e) {
                    LogUtil.e("中断异常", e);
                }
                return null;
            }

            @SuppressWarnings("deprecation")
            @Override
            protected void onPostExecute(Void result) {
                // 执行完毕以后：按钮回复原状
                mVerificationTv.setClickable(true);
                mVerificationTv.setText("获取验证码");
            }

            @Override
            protected void onProgressUpdate(Integer... values) {
                int countdown = 0;
                if (values.length > 0) {
                    countdown = values[0];
                }
                mVerificationTv.setText(countdown + "");
            }
        }.execute();
    }

}